package cn.hdu.liang.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

public class NIOUtil {
    public static void dump(ReadableByteChannel src, WritableByteChannel dest) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(32);

        try(ReadableByteChannel srcCH = src;
            WritableByteChannel destCH = dest) {
            while(srcCH.read(buffer) != -1) {
                buffer.flip();
                destCH.write(buffer);
                buffer.clear();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        ReadableByteChannel src = Channels.newChannel(new FileInputStream("temp.txt"));
        WritableByteChannel dest = new FileOutputStream("temp2.txt").getChannel();
        NIOUtil.dump(src, dest);
    }
}
